//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.agency;

import java.awt.Dimension;
import java.awt.event.*;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.gui.progressBar.ProgressBar;
import org.jpgolay.gui.progressBar.SwingWorker;
import org.jpgolay.wi.group.Group;
import org.jpgolay.wi.group.GroupCRUD;
import org.jpgolay.wi.list.ListController;
import org.jpgolay.wi.user.User;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.WIDate;

// Referenced classes of package org.jpgolay.wi.agency:
//            AgencyGUI, AgencyCRUD, AgencyList, Agency
public class AgencyController {

    private class MouseClickList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            actionSelectAgency();
        }

        MouseClickList() {
        }
    }

    public AgencyController() {
        id = "";
        action = 0;
        initComponent();
        date = new WIDate();
        aGui.editableFields(false);
    }

    private boolean initComponent() {
        if (crud == null) {
            crud = new AgencyCRUD();
            crudGroup = new GroupCRUD();
        }
        if (aGui == null || aGui.isClosed()) {
            aGui = new AgencyGUI();
            aGui.setIconifiable(true);
            aGui.setResizable(false);
            aGui.setMaximizable(false);
            aGui.setClosable(true);
            aGui.setVisible(true);
            aGui.toFront();
            aGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent actionevent) {
                }
            });
            aGui.getNewMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCreate();
                }
            });
            aGui.getOpenMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionOpen();
                }
            });
            aGui.getModifyMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionModify();
                }
            });
            aGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionSave();
                }
            });
            aGui.getRemoveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionRemove();
                }
            });
            aGui.getHelpMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionHelp();
                }
            });
            aGui.getPrintMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    PrinterJob pj = PrinterJob.getPrinterJob();
                    if (pj.printDialog()) {
                        actionPrint();
                    }
                }
            });
            aGui.getIconBar1().addAnswerListener(new AnswerListener() {
                public void create(AnswerEvent e) {
                    actionCreate();
                }

                public void open(AnswerEvent e) {
                    actionOpen();
                }

                public void modify(AnswerEvent e) {
                    actionModify();
                }

                public void save(AnswerEvent e) {
                    actionSave();
                }

                public void remove(AnswerEvent e) {
                    actionRemove();
                }

                public void print(AnswerEvent e) {
                    actionPrint();
                }

                public void help(AnswerEvent e) {
                    actionHelp();
                }
            });
            aGui.setAllGroupId(getAllGroup());
            return true;
        }
        if (aGui.isIcon()) {
            try {
                aGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        aGui.toFront();
        return false;
    }

    public boolean init() {
        if (aGui == null || aGui.isClosed()) {
            boolean result = initComponent();
            aGui.editableFields(false);
            if (result) {
                setLaw();
            }
            return result;
        }
        if (aGui.isIcon()) {
            try {
                aGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        aGui.toFront();
        return false;
    }

    private void actionCreate() {
        if (action == 2) {
            JOptionPane.showMessageDialog(aGui, "Modification en cours !");
        } else {
            action = 1;
            aGui.initFields();
            aGui.editableFields(true);
        }
    }

    private void actionOpen() {
        aGui.initFields();
        aGui.editableFields(false);
        openList();
    }

    private void actionModify() {
        if (action == 1) {
            JOptionPane.showMessageDialog(aGui, "Modification impossible !");
        } else {
            action = 2;
            aGui.editableFields(true);
        }
    }

    private void actionSave() {
        if (action == 2 || action == 1) {
            setAgency();
        } else {
            JOptionPane.showMessageDialog(aGui, "Aucunes donn\351es \340 sauvegarder !");
        }
    }

    private void actionRemove() {
        if (action == 2) {
            remove();
        } else {
            JOptionPane.showMessageDialog(aGui, "Aucunes donn\351es \340 supprimer !");
        }
    }

    private void actionPrint() {
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void actionSelectAgency() {
        getAgency(new Integer(lCtrl.getContenuT().getValueAt(lCtrl.getContenuT().getSelectedRow(), 0).toString()));
        lCtrl.hidden();
    }

    private void getAgency(Integer id) {
        final Integer ID = id;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                if (crud.find(ID)) {
                    agency = crud.getData();
                    aGui.setAccess(agency.getAccess().intValue());
                    aGui.setGroupId(indexGroup.indexOf(agency.getGroupId()));
                    aGui.setAddrLn1(agency.getAddrLn1());
                    aGui.setAddrLn2(agency.getAddrLn2());
                    aGui.setCity(agency.getCity());
                    aGui.setComment(agency.getComment());
                    aGui.setCompagny(agency.getCompagny());
                    aGui.setCompagnyNaf(agency.getNaf());
                    aGui.setCompagnySiret(agency.getSiret());
                    aGui.setCounty(agency.getCounty());
                    aGui.setEmail(agency.getEmail());
                    aGui.setExpiryDate(agency.getExpiryDate());
                    aGui.setFax(agency.getFax());
                    aGui.setId(agency.getId().toString());
                    aGui.setLastUpdate(agency.getLastUpdate());
                    aGui.setLastUser(agency.getLastUser());
                    aGui.setLogo(agency.getLogo());
                    aGui.setNewAdEmailDown(agency.getNewAdEmailDown());
                    aGui.setNewAdEmailUp(agency.getNewAdEmailUp());
                    aGui.setNewAdTitle(agency.getNewAdTitle());
                    aGui.setPass(agency.getPass());
                    aGui.setPaymentDue(agency.getPaymentDue().toString());
                    aGui.setSmtp(agency.getSmtp());
                    aGui.setStatus(agency.getStatus());
                    aGui.setTel1(agency.getTel1());
                    aGui.setTel2(agency.getTel2());
                    aGui.setUsername(agency.getUsername());
                    aGui.setWeb(agency.getWeb());
                    aGui.setWelcomeEmail(agency.getWelcomeEmail());
                    aGui.setWelcomeTitle(agency.getWelcomeTitle());
                    aGui.setWww(agency.getWww());
                    aGui.setZip(agency.getZip());
                } else {
                    JOptionPane.showMessageDialog(aGui, "Impossible de r\351cuperer l'agence !");
                }
                stopProgressBar();
                return null;
            }
        };
        worker.start();
    }

    private void setAgency() {
        if (verifyRequis()) {
            SwingWorker worker = new SwingWorker() {
                public Object construct() {
                    startProgressBar();
                    if (aGui.getId().equals("")) {
                        if (crud.create()) {
                            agency = crud.getData();
                            agency.setGroupId(new Integer(aGui.getGroupId()));
                            agency.setAccess(new Integer(aGui.getAccess()));
                            agency.setAddrLn1(aGui.getAddrLn1());
                            agency.setAddrLn2(aGui.getAddrLn2());
                            agency.setCity(aGui.getCity());
                            agency.setComment(aGui.getComment());
                            agency.setCompagny(aGui.getCompagny());
                            agency.setNaf(aGui.getCompagnyNaf());
                            agency.setSiret(aGui.getCompagnySiret());
                            agency.setCounty(aGui.getCounty());
                            agency.setEmail(aGui.getEmail());
                            agency.setExpiryDate(aGui.getExpiryDate());
                            agency.setFax(aGui.getFax());
                            agency.setLastUser(user.getId().toString());
                            agency.setLogo(aGui.getLogo());
                            agency.setNewAdEmailDown(aGui.getNewAdEmailDown());
                            agency.setNewAdEmailUp(aGui.getNewAdEmailUp());
                            agency.setNewAdTitle(aGui.getNewAdTitle());
                            agency.setPass(aGui.getPass());
                            agency.setPaymentDue(new BigDecimal(aGui.getPaymentDue()));
                            agency.setSmtp(aGui.getSmtp());
                            agency.setStatus(aGui.getStatus());
                            agency.setTel1(aGui.getTel1());
                            agency.setTel2(aGui.getTel2());
                            agency.setUsername(aGui.getUsername());
                            agency.setWeb(aGui.getWeb());
                            agency.setWelcomeEmail(aGui.getWelcomeEmail());
                            agency.setWelcomeTitle(aGui.getWelcomeTitle());
                            agency.setWww(aGui.getWww());
                            agency.setZip(aGui.getZip());
                            crud.setData(agency);
                            if (crud.modify()) {
                                aGui.editableFields(false);
                                action = 0;
                            } else {
                                JOptionPane.showMessageDialog(aGui, "Impossible de r\351cuperer l'agence !\n(un autre utilisateur l'a peut-\352tre modifi\351e)");
                            }
                        } else {
                            JOptionPane.showMessageDialog(aGui, "Impossible de r\351cuperer l'agence !\n(un autre utilisateur l'a peut-\352tre supprim\351)");
                        }
                    } else if (crud.find(new Integer(aGui.getId()))) {
                        agency = crud.getData();
                        agency.setGroupId(new Integer(aGui.getGroupId()));
                        agency.setAccess(new Integer(aGui.getAccess()));
                        agency.setAddrLn1(aGui.getAddrLn1());
                        agency.setAddrLn2(aGui.getAddrLn2());
                        agency.setCity(aGui.getCity());
                        agency.setComment(aGui.getComment());
                        agency.setCompagny(aGui.getCompagny());
                        agency.setNaf(aGui.getCompagnyNaf());
                        agency.setSiret(aGui.getCompagnySiret());
                        agency.setCounty(aGui.getCounty());
                        agency.setEmail(aGui.getEmail());
                        agency.setExpiryDate(aGui.getExpiryDate());
                        agency.setFax(aGui.getFax());
                        agency.setLastUpdate(aGui.getLastUpdate());
                        agency.setLastUser(user.getId().toString());
                        agency.setLogo(aGui.getLogo());
                        agency.setNewAdEmailDown(aGui.getNewAdEmailDown());
                        agency.setNewAdEmailUp(aGui.getNewAdEmailUp());
                        agency.setNewAdTitle(aGui.getNewAdTitle());
                        agency.setPass(aGui.getPass());
                        agency.setPaymentDue(new BigDecimal(aGui.getPaymentDue()));
                        agency.setSmtp(aGui.getSmtp());
                        agency.setStatus(aGui.getStatus());
                        agency.setTel1(aGui.getTel1());
                        agency.setTel2(aGui.getTel2());
                        agency.setUsername(aGui.getUsername());
                        agency.setWeb(aGui.getWeb());
                        agency.setWelcomeEmail(aGui.getWelcomeEmail());
                        agency.setWelcomeTitle(aGui.getWelcomeTitle());
                        agency.setWww(aGui.getWww());
                        agency.setZip(aGui.getZip());
                        crud.setData(agency);
                        if (crud.modify()) {
                            aGui.editableFields(false);
                            action = 0;
                        } else {
                            JOptionPane.showMessageDialog(aGui, "Impossible de modifi\351e l'agence !\n(un autre utilisateur l'a peut-\352tre modifi\351e)");
                        }
                    } else {
                        JOptionPane.showMessageDialog(aGui, "Impossible de r\351cuperer l'agence !\n(un autre utilisateur l'a peut-\352tre supprim\351)");
                    }
                    stopProgressBar();
                    return null;
                }
            };
            worker.start();
        }
    }

    private void remove() {
        int reponse = JOptionPane.showConfirmDialog(aGui, "Voulez-vous vraiment supprimer l'agence num\351ro " + aGui.getId() + " ?" + "\nATTENTION tous les biens rattach\351s \340 cette agence, ainsi que " + "\ntous ces utilisateurs seront d\351finitivement perdus !", "Confirmation", 1, 2, null);
        switch (reponse) {
            default:
                break;

            case 0: // '\0'
                if (crud.find(new Integer(aGui.getId()))) {
                    if (crud.remove()) {
                        aGui.initFields();
                        aGui.editableFields(false);
                        action = 0;
                    } else {
                        JOptionPane.showMessageDialog(aGui, "Impossible de supprimer l'agence  (" + aGui.getId() + ") !" + "\nUn autre utilisateur l'a peut-\352tre modifi\351 entre temps.");
                    }
                } else {
                    JOptionPane.showMessageDialog(aGui, "Impossible de trouver l'agence  (" + aGui.getId() + ") !" + "\nUn autre utilisateur l'a peut-\352tre supprimer entre temps.");
                }
            // fall through

            case 1: // '\001'
                aGui.editableFields(false);
                action = 0;
                break;

            case 2: // '\002'
                aGui.editableFields(false);
                action = 0;
                break;

            case -1:
                aGui.editableFields(false);
                action = 0;
                break;
        }
    }

    private boolean verifyRequis() {
        if (aGui.getAddrLn1().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Adresse ligne 1 trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getAddrLn2().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Adresse ligne 2 trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getCity().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Ville trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getComment().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Commentaire trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getCompagny().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Soci\351t\351 trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getCompagnyNaf().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Naf trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getCompagnySiret().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Siret trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getCounty().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Commune trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getEmail().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "E-mail trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getFax().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Fax trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getNewAdEmailDown().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Mail annonce inferieur trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getNewAdEmailUp().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Mail annonce sup\351rieur trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getNewAdTitle().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Titre mail annonce trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getPass().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Mot de passe trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getPass().length() < 4) {
            JOptionPane.showMessageDialog(aGui, "Mot de passe requis !\n(minimum 4 caract\350res)");
            return false;
        }
        if (aGui.getSmtp().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Smtp trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getStatus().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Status trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getTel1().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "T\351l 1 trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getTel2().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "T\351l 2 trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getUsername().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Nom d'utilisateur trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getWeb().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Web trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getWelcomeEmail().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Mail de bienvenue trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getWelcomeTitle().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "Titre mail de bienvenue trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getWww().length() > 250) {
            JOptionPane.showMessageDialog(aGui, "WWW trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (aGui.getZip().length() > 5) {
            JOptionPane.showMessageDialog(aGui, "Code postal trop long !\n(maximum 5 caract\350res)");
            return false;
        }
        if (aGui.getPaymentDue().equals("")) {
            aGui.setPaymentDue("0");
        }
        if (!date.isValid(aGui.getExpiryDate())) {
            aGui.setExpiryDate("");
        }
        try {
            new BigDecimal(aGui.getPaymentDue());
        } catch (NumberFormatException nfe3) {
            JOptionPane.showMessageDialog(aGui, "Le montant Paiement du est invalide !");
            return false;
        }
        try {
            new Integer(aGui.getZip());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(aGui, "Code postal invalide !\n(nombre entier uniquement)");
            return false;
        }
        if (action == 1 && crud.isPassword(aGui.getPass())) {
            JOptionPane.showMessageDialog(aGui, "Le mot de passe (" + aGui.getPass() + ") existe d\351j\340 !");
            return false;
        } else {
            return true;
        }
    }

    private String[] getAllGroup() {
        ArrayList list = new ArrayList(crudGroup.findAll());
        if (list != null && list.size() > 0) {
            Iterator it = list.iterator();
            String l[] = new String[list.size()];
            indexGroup = new ArrayList();
            for (int i = 0; it.hasNext(); i++) {
                group = (Group) it.next();
                l[i] = group.getId().toString() + " " + group.getName();
                indexGroup.add(group.getId());
            }

            return l;
        } else {
            String e[] = {
                "Aucun group"
            };
            return e;
        }
    }

    public void iconified() {
        if (aGui != null) {
            aGui.setVisible(false);
        }
    }

    public void unIconified() {
        if (aGui != null) {
            aGui.setVisible(true);
        }
    }

    public void maximizeFrame() {
        try {
            aGui.setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void startProgressBar() {
        if (pb == null) {
            pb = new ProgressBar(null, false);
            pb.setLocationRelativeTo(aGui);
            aGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        } else {
            aGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        }
    }

    private void stopProgressBar() {
        if (!pb.isStop()) {
            pb.stop();
            pb.setVisible(false);
            aGui.setEnabled(true);
        }
    }

    private void setLaw() {
        String b = Long.toBinaryString(user.getAccess().intValue());
        int position = b.length();
        if ((position -= 12) >= 0 && b.charAt(position) == '1') {
            aGui.getNewMI().setEnabled(true);
            aGui.getModifyMI().setEnabled(true);
            aGui.getRemoveMI().setEnabled(true);
            aGui.getSaveMI().setEnabled(true);
            aGui.getIconBar1().setEnabledCreate(true);
            aGui.getIconBar1().setEnabledModify(true);
            aGui.getIconBar1().setEnabledRemove(true);
            aGui.getIconBar1().setEnabledSave(true);
        }
    }

    public void setUser(User user) {
        this.user = user;
        setLaw();
    }

    public AgencyGUI getGUI() {
        return aGui;
    }

    public void setJDesktopPane(JDesktopPane desktop) {
        this.desktop = desktop;
    }

    private void openList() {
        if (lCtrl == null) {
            lCtrl = new ListController("logo.gif", desktop, "Liste des AGENCES", AgencyList.CB_MODEL, AgencyList.COLUMN_NAME);
            lCtrl.setPreferredColumnSize(AgencyList.COLUMN_SIZE);
            lCtrl.setRequestChoice(AgencyList.REQUESTS);
            lCtrl.setRequestLikeChoice(AgencyList.REQUESTS_LIKE);
            lCtrl.setRequestErrorMsg(AgencyList.ERROR_MSG);
            lCtrl.getContenuT().addMouseListener(new MouseClickList());
        } else {
            lCtrl.getContenuT().addMouseListener(new MouseClickList());
            lCtrl.show();
        }
        lCtrl.search();
    }

    private void closeList() {
        lCtrl.close();
    }
    private AgencyGUI aGui;
    private AgencyCRUD crud;
    private GroupCRUD crudGroup;
    private Agency agency;
    private User user;
    private Group group;
    private Dimension screen;
    private WIDate date;
    private ProgressBar pb;
    private ListController lCtrl;
    private ArrayList indexGroup;
    private String id;
    private int action;
    private final int CREATE = 1;
    private final int MODIFY = 2;
    private JDesktopPane desktop;
}
